const User = require('../models/user');
const Student = require('../models/student');
const Teacher = require('../models/teacher');
const { hashPassword } = require('../utils/passwordUtils');

class UserController {
  /**
   * 获取用户个人资料
   * @param {Koa.Context} ctx - Koa上下文
   */
  static async getProfile(ctx) {
    try {
      const userId = ctx.user?.id;
      
      const user = await User.findById(userId)
        .select('-password -__v')
        .exec();
      
      if (!user) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '用户不存在'
        };
        return;
      }
      
      // 根据角色获取详细信息
      let detailedInfo = null;
      if (user.role === 'student') {
        detailedInfo = await Student.findOne({ user: userId }).exec();
      } else if (user.role === 'teacher') {
        detailedInfo = await Teacher.findOne({ user: userId }).exec();
      }
      
      ctx.body = {
        success: true,
        data: {
          user,
          detailedInfo
        },
        message: '获取个人资料成功'
      };
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        success: false,
        message: error.message || '获取个人资料失败'
      };
    }
  }

  /**
   * 更新用户个人资料
   * @param {Koa.Context} ctx - Koa上下文
   */
  static async updateProfile(ctx) {
    try {
      const userId = ctx.user?.id;
      const updates = ctx.request.body;
      
      // 不允许更新的字段
      delete updates.username;
      delete updates.password;
      delete updates.role;
      delete updates._id;
      
      const user = await User.findByIdAndUpdate(
        userId,
        updates,
        { new: true, runValidators: true }
      )
        .select('-password -__v')
        .exec();
      
      if (!user) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '用户不存在'
        };
        return;
      }
      
      // 如果有详细信息更新
      if (updates.detailedInfo) {
        const { detailedInfo } = updates;
        
        if (user.role === 'student') {
          await Student.findOneAndUpdate(
            { user: userId },
            detailedInfo,
            { upsert: true, new: true, runValidators: true }
          ).exec();
        } else if (user.role === 'teacher') {
          await Teacher.findOneAndUpdate(
            { user: userId },
            detailedInfo,
            { upsert: true, new: true, runValidators: true }
          ).exec();
        }
      }
      
      ctx.body = {
        success: true,
        data: user,
        message: '更新个人资料成功'
      };
    } catch (error) {
      ctx.status = error.status || 400;
      ctx.body = {
        success: false,
        message: error.message || '更新个人资料失败'
      };
    }
  }

  /**
   * 获取用户列表（仅管理员和老师可访问）
   * @param {Koa.Context} ctx - Koa上下文
   */
  static async getUsers(ctx) {
    try {
      const { page = 1, limit = 20, role, status } = ctx.query;
      const userRole = ctx.user?.role;
      
      // 检查权限
      if (userRole !== 'admin' && userRole !== 'teacher') {
        ctx.status = 403;
        ctx.body = {
          success: false,
          message: '无权访问此资源'
        };
        return;
      }
      
      const query = {};
      
      // 添加角色过滤
      if (role) {
        query.role = role;
      }
      
      // 添加状态过滤
      if (status) {
        query.status = status;
      }
      
      const skip = (page - 1) * limit;
      const users = await User.find(query)
        .select('-password -__v')
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(parseInt(limit))
        .exec();
      
      const total = await User.countDocuments(query);
      
      ctx.body = {
        success: true,
        data: {
          users,
          pagination: {
            total,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(total / limit)
          }
        },
        message: '获取用户列表成功'
      };
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        success: false,
        message: error.message || '获取用户列表失败'
      };
    }
  }

  /**
   * 根据ID获取用户信息（仅管理员和老师可访问）
   * @param {Koa.Context} ctx - Koa上下文
   */
  static async getUserById(ctx) {
    try {
      const { id } = ctx.params;
      const userRole = ctx.user?.role;
      
      // 检查权限
      if (userRole !== 'admin' && userRole !== 'teacher') {
        ctx.status = 403;
        ctx.body = {
          success: false,
          message: '无权访问此资源'
        };
        return;
      }
      
      const user = await User.findById(id)
        .select('-password -__v')
        .exec();
      
      if (!user) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '用户不存在'
        };
        return;
      }
      
      // 根据角色获取详细信息
      let detailedInfo = null;
      if (user.role === 'student') {
        detailedInfo = await Student.findOne({ user: id }).exec();
      } else if (user.role === 'teacher') {
        detailedInfo = await Teacher.findOne({ user: id }).exec();
      }
      
      ctx.body = {
        success: true,
        data: {
          user,
          detailedInfo
        },
        message: '获取用户信息成功'
      };
    } catch (error) {
      ctx.status = error.status || 500;
      ctx.body = {
        success: false,
        message: error.message || '获取用户信息失败'
      };
    }
  }
}

module.exports = UserController;